package com.rand.beauty;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.example.android.bitmapfun.util.DiskLruCache;

import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

public class SaveImgToDo {

	enum WhatToDo {
		Save_To_Ablum, Save_To_SetWallPaper, Favourite
	}

	private Context myContext;
	public Bitmap myBitmap;

	public SaveImgToDo(Context context) {
		this.myContext = context;
	}

	void Run(WhatToDo todo, String url) {
		MyRunnable runnable = new MyRunnable();
		runnable.myTodo = todo;
		runnable.myUrl = url;
		ThreadPoolUtils.execute(runnable);
	}

	public class MyRunnable implements Runnable {
		@Override
		public void run() {
			ToastUtil.showMessage(myContext, "图片下载中...");
			String fileName = KeyFilterUtils.MD5(myUrl) + ".jpg";
			if (!DownFiletoDecive(myUrl, fileName)) {
				ToastUtil.showMessage(myContext, "下载失败");
			} else {
				if (myTodo == WhatToDo.Save_To_Ablum) {
					SaveToAblum(myBitmap, fileName);
				} else if (myTodo == WhatToDo.Save_To_SetWallPaper) {
					SetToBeWallPaper(myBitmap, fileName);
				} else if (myTodo == WhatToDo.Favourite) {
					FavouritePic(myBitmap, fileName);
				}
			}
		}

		public String myUrl;
		public WhatToDo myTodo;
	}

	public boolean DownFiletoDecive(String url, String filename) {
		if ((url != null && !"".equals(url))
				&& (filename != null && !"".equals(filename))) {
			try {
				InputStream input = getInputStreamFromUrl(url);
				myBitmap = BitmapFactory.decodeStream(input);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			} finally {
			}
		}

		return true;
	}

	public InputStream getInputStreamFromUrl(String urlStr)
			throws MalformedURLException, IOException {
		URL url = new URL(urlStr);
		HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
		InputStream inputStream = urlCon.getInputStream();
		return inputStream;
	}

	void SetToBeWallPaper(Bitmap bitmap, String fileName) {

		WallpaperManager wallpaperManager = WallpaperManager
				.getInstance(myContext);
		try {
			wallpaperManager.setBitmap(bitmap);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ToastUtil.showMessage(myContext, "设置失败");
		} finally {
			bitmap.recycle();
		}

		ToastUtil.showMessage(myContext, "设置壁纸成功");
	}

	void SaveToAblum(Bitmap bitmap, String fileName) {
		MediaStore.Images.Media.insertImage(myContext.getContentResolver(),
				bitmap, fileName, "妹子图片");
		myContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
				.parse("file://" + Environment.getExternalStorageDirectory())));
		ToastUtil.showMessage(myContext, "保存到相册成功");
		bitmap.recycle();
	}

	void FavouritePic(Bitmap bitmap, String fileName) {
		final File cacheDir = DiskLruCache.getDiskCacheDir(myContext,
				"favourite");

		final DiskLruCache cache = DiskLruCache.openCache(myContext, cacheDir,
				50 * 1024 * 1024);
		
		if (!cache.containsKey(fileName)) {

			final File cacheFile = new File(cache.createFilePath(fileName));
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
			byte[] bitmapdata = bos.toByteArray();

			KeyFilterUtils.SaveImageInfo(fileName, bitmap.getHeight(), bitmap.getWidth(), myContext);
			
			// write the bytes in file
			FileOutputStream fos;
			try {
				fos = new FileOutputStream(cacheFile);
				fos.write(bitmapdata);
				ToastUtil.showMessage(myContext, "已收藏");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				ToastUtil.showMessage(myContext, "收藏失败");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				ToastUtil.showMessage(myContext, "收藏失败");
			}
		}

		bitmap.recycle();
	}
}
